-module(ehttp_util).

-export([
    to_binary/1
    ,list_to_atom/1
    ,fix_middle/1
    ,time_diff/2
]).


%% 浮点数直接用 float_to_list(Float) 会用科学计数法表示并可能有误差，直接调用 float_to_list(Float, [{decimals, 长度}])
to_binary(Data) when erlang:is_binary(Data) -> Data;
to_binary(Data) when erlang:is_atom(Data) -> list_to_binary(atom_to_list(Data));
to_binary(Data) when erlang:is_list(Data) -> list_to_binary(Data);
to_binary(Data) when erlang:is_integer(Data) -> list_to_binary(integer_to_list(Data));
to_binary(Data) when erlang:is_float(Data) -> float_to_binary(Data);
to_binary(_Data) -> <<>>.

list_to_atom(List)->
    try
        erlang:list_to_existing_atom(List)
    catch _:_ ->
        erlang:list_to_atom(List)
    end.

fix_middle(undefined) -> [];
fix_middle(Middles = [_|_]) -> Middles;
fix_middle(Middle) -> [Middle].

time_diff({MegaSecs, Secs, MicroSecs}, {MegaSecs, Secs2, MicroSecs2}) ->
    Secs2 * 1000000 + MicroSecs2 - Secs * 1000000 - MicroSecs;
time_diff({MegaSecs, Secs, MicroSecs}, {MegaSecs2, Secs2, MicroSecs2}) ->
    MegaSecs2 * 1000000000000  + Secs2 * 1000000 + MicroSecs2 - MegaSecs * 1000000000000 - Secs * 1000000 - MicroSecs.
